﻿/*
 * 欢迎使用RoadFlowCore工作流系统，当前版本2.8.2
 * 重庆天知软件技术有限公司版权所有
 */
using System;
using System.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RoadFlow.Mvc.Models;
using RoadFlow.Utility;

namespace RoadFlow.Mvc.Controllers
{
    public class HomeController : Controller
    {
        [Validate(CheckUrl = false)]
        public IActionResult Index()
        {
            Guid userId = Current.UserId;
            Model.User CurrentUserModel = Current.User;
            Business.User user = new Business.User();
            Business.Menu menu = new Business.Menu();

            //得到未读消息
            var (noReadMsg, count) = new Business.Message().GetNoRead(userId);
            string noReadMsgHtml = "";
            if (noReadMsg != null && count > 0)
            {
                string contents = noReadMsg.Contents;
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", noReadMsg.Id.ToString() },
                    { "title", noReadMsg.Type==1 ? "待办事项" : "未读消息" },
                    { "contents", contents },
                    { "count", count }
                };
                noReadMsgHtml = jObject.ToString(Newtonsoft.Json.Formatting.None);
            }

            ViewData["noReadMsgHtml"] = noReadMsgHtml;
            ViewData["menu"] = menu.GetUserMenuHtml(userId);//得到用户菜单
            ViewData["menumin"] = menu.GetUserMinMenuHtml(userId);//得到用户小菜单
            ViewData["headImage"] = user.GetHeadImageSrc(CurrentUserModel, Current.WebRootPath);
            ViewData["userName"] = CurrentUserModel.Name;
            ViewData["currentDate"] = DateExtensions.Now.ToLongDate();
            ViewData["loginURL"] = Config.LoginUrl;
            ViewData["rootDir"] = Url.Content("~/").Equals("/") ? "" : Url.Content("~/");
            return View();
        }

        [Validate(CheckApp = false)]
        /// <summary>
        /// 加载二级菜单
        /// </summary>
        /// <returns></returns>
        public string MenuRefresh1()
        {
            string refreshID = Request.Querys("refreshid");
            string isrefresh1 = Request.Querys("isrefresh1");
            Guid uid = Current.UserId;
            if (!refreshID.IsGuid(out Guid refreshid))
            {
                return "";
            }
            if (refreshid.IsNotEmptyGuid())
            {
                return new Business.Menu().GetUserMenuChilds(uid, refreshid, Url.Content("~/").TrimEnd('/'), isrefresh1);
            }
            else
            {
                return "";
            }
        }
        
        public IActionResult Login()
        {
            string isVcode = HttpContext.Session.GetString("rf_validatecode");
            ViewData["isVcode"] = isVcode.IsNullOrWhiteSpace() ? "0" : isVcode;
            ViewData["isSession"] = Request.Querys("issession");
            return View();
        }

        /// <summary>
        /// 在当前页面登录
        /// </summary>
        /// <returns></returns>
        public IActionResult Login1()
        {
            string isVcode = HttpContext.Session.GetString("rf_validatecode");
            ViewData["isVcode"] = isVcode.IsNullOrWhiteSpace() ? "0" : isVcode;
            return View();
        }
        
        /// <summary>
        /// 验证用户登录
        /// </summary>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        public string CheckLogin()
        {
            string Account = Request.Forms("Account");
            string Password = Request.Forms("Password");
            string VCode = Request.Forms("VCode");
            string Force = Request.Forms("Force");
            string logContent = "帐号：" + Account + " 密码：" + Password + " 验证码：" + VCode;
            Business.User user = new Business.User();
            if (Account.IsNullOrWhiteSpace() || Password.IsNullOrWhiteSpace())
            {
                HttpContext.Session.SetString("rf_isvalidatecode", "1");//是否要验证验证码
                Business.Log.Add("用户登录失败 - 帐号密码不能为空", logContent, Business.Log.Type.用户登录);
                return "{\"status\":0,\"msg\":\"帐号密码不能为空!\"}";
            }
            string vcodeSession = HttpContext.Session.GetString("rf_validatecode");
            if ("1".Equals(HttpContext.Session.GetString("rf_isvalidatecode")) && !vcodeSession.EqualsIgnoreCase(VCode))
            {
                HttpContext.Session.SetString("rf_isvalidatecode", "1");//是否要验证验证码
                return "{\"status\":0,\"msg\":\"验证码错误!\"}";
            }
            var userModel = user.GetByAccount(Account.Trim());
            if (null == userModel)
            {
                HttpContext.Session.SetString("rf_isvalidatecode", "1");//是否要验证验证码
                Business.Log.Add("用户登录失败 - 帐号:" + Account, logContent, Business.Log.Type.用户登录);
                return "{\"status\":0,\"msg\":\"帐号错误!\"}";
            }
            if (userModel.Password.IsNullOrWhiteSpace() || !userModel.Password.EqualsIgnoreCase(user.GetMD5Password(userModel.Id, Password)))
            {
                HttpContext.Session.SetString("rf_isvalidatecode", "1");//是否要验证验证码
                Business.Log.Add("用户登录失败 - 帐号:" + Account, logContent, Business.Log.Type.用户登录);
                return "{\"status\":0,\"msg\":\"密码错误!\"}";
            }
            if (user.IsFrozen(userModel))
            {
                HttpContext.Session.SetString("rf_isvalidatecode", "1");//是否要验证验证码
                Business.Log.Add("用户登录失败 - 用户已被冻结-" + userModel.Account, "", Business.Log.Type.用户登录);
                return "{\"status\":0,\"msg\":\"用户已被冻结!\"}";
            }
            //验证单点登录
            if (Config.SingleLogin)
            {
                var ouModel = Business.OnlineUser.Get(userModel.Id);
                string cookieUniqueId = HttpContext.Request.Cookies.TryGetValue("rf_login_uniqueid", out string v) ? v : "";
                if (null != ouModel && "0".Equals(Force) && !ouModel.UniqueId.Equals(cookieUniqueId))
                {
                    return "{\"status\":2,\"msg\":\"用户已在" + ouModel.IP + "登录，您要强行登录吗?\"}";
                }
            }

            HttpContext.Session.Remove("rf_isvalidatecode");
            HttpContext.Session.SetString(Config.UserIdSessionKey, userModel.Id.ToString());

            //添加到在线用户字典
            string uniqueId = Guid.NewGuid().ToUpperString();
            HttpContext.Response.Cookies.Append("rf_login_uniqueid", uniqueId.ToString(), new CookieOptions() { Expires = Current.DateTime.AddYears(1)});
            Model.OnlineUser onlineUserModel = new Model.OnlineUser
            {
                UserId = userModel.Id,
                UserName = userModel.Name,
                UserOrganize = user.GetOrganizeMainShowHtml(userModel.Id, false),
                IP = Tools.GetIP(),
                LastTime = Current.DateTime,
                LastUrl = Request.Path.HasValue ? Request.Path.Value : "",
                LoginType = 0,
                UniqueId = uniqueId,
                BrowseAgent = Tools.GetBrowseAgent()
            };
            onlineUserModel.LoginTime = onlineUserModel.LastTime;
            Business.OnlineUser.Add(onlineUserModel);
            Business.Log.Add("用户登录成功-" + userModel.Account, "", Business.Log.Type.用户登录);
            return "{\"status\":1,\"msg\":\"登录成功!\"}";
        }

        public void VCode()
        {
            string bgImg = Current.WebRootPath + "/RoadFlowResources/images/vcodebg.png";
            System.IO.MemoryStream ms = Tools.GetValidateImg(out string code, bgImg);
            HttpContext.Session.SetString("rf_validatecode", code);
            Response.Clear();
            Response.ContentType = "image/png";
            Response.Body.Write(ms.GetBuffer(), 0, (int)ms.Length);
            Response.Body.Flush();
            Response.Body.Close();
        }

        public IActionResult Quit()
        {
            ClearSession();
            return Redirect("~/Home/Login");
        }

        /// <summary>
        /// 清除用户在线信息
        /// </summary>
        /// <returns></returns>
        public string ClearSession()
        {
            Business.OnlineUser.Remove(Current.UserId);
            HttpContext.Session.Clear();
            return "";
        }

        [Validate(CheckApp = false)]
        public IActionResult Home()
        {
            return View();
        }

        [Validate(CheckApp = false)]
        public string Menu()
        {
            string userid = Request.Querys("userid");
            Guid uid = userid.IsGuid(out Guid guid) ? guid : Current.UserId;
            bool showSource = "1".Equals(Request.Querys("showsource"));
            if (uid.IsEmptyGuid())
            {
                return "[]";
            }
            else
            {
                return new Business.Menu().GetUserMenuJsonString(uid, Url.Content("~/").TrimEnd('/'), showSource);
            }
        }

        [Validate(CheckApp = false)]
        public string MenuRefresh()
        {
            string userid = Request.Querys("userid");
            string refreshID = Request.Querys("refreshid");
            bool showSource = "1".Equals(Request.Querys("showsource"));
            Guid uid = userid.IsGuid(out Guid guid) ? guid : Current.UserId;
            if (!refreshID.IsGuid(out Guid refreshid))
            {
                return "[]";
            }
            if (!refreshid.IsEmptyGuid())
            {
                return new Business.Menu().GetUserMenuRefreshJsonString(uid, refreshid, Url.Content("~/").TrimEnd('/'), showSource);
            }
            else
            {
                return "[]";
            }
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
